<!-- pages/user/profile.vue -->
<template>
  <view class="profile-container">
    <!-- 自定义导航栏 -->
    <uni-nav-bar 
      title="个人中心"
      left-icon="left"
      @clickLeft="navigateBack"
      fixed
      status-bar
    />

    <!-- 用户头像 -->
    <view class="avatar-section" @click="changeAvatar">
      <image class="avatar" :src="formData.avatar" mode="aspectFill" />
      <uni-icons class="edit-icon" type="compose" size="24" color="#fff" />
    </view>

    <!-- 用户信息表单 -->
    <uni-forms ref="form" :modelValue="formData" :rules="rules">
      <uni-card>
        <!-- 基本信息 -->
        <uni-forms-item label="姓名" required name="name">
          <uni-easyinput v-model="formData.name" placeholder="请输入真实姓名" />
        </uni-forms-item>

        <uni-forms-item label="性别" required name="gender">
          <uni-data-checkbox v-model="formData.gender" :localdata="genders" />
        </uni-forms-item>

        <uni-forms-item label="出生日期" required name="birth_date">
          <uni-datetime-picker 
            type="date" 
            v-model="formData.birth_date"
          />
        </uni-forms-item>

        <!-- 证件信息 -->
        <uni-forms-item label="证件类型" required name="id_type">
          <uni-data-select 
            v-model="formData.id_type"
            :localdata="idTypes"
          />
        </uni-forms-item>

        <uni-forms-item label="证件号码" required name="id_number">
          <uni-easyinput 
            v-model="formData.id_number"
            placeholder="请输入证件号码"
          />
        </uni-forms-item>

        <!-- 联系方式 -->
        <uni-forms-item label="手机号" required name="phone">
          <uni-easyinput 
            v-model="formData.phone" 
            type="number"
            placeholder="请输入手机号"
          />
        </uni-forms-item>

        <uni-forms-item label="邮箱" name="email">
          <uni-easyinput 
            v-model="formData.email"
            type="email"
            placeholder="请输入邮箱"
          />
        </uni-forms-item>

        <!-- 地址信息 -->
        <uni-forms-item label="所在地区" required>
          <uni-data-picker 
            placeholder="请选择省市区"
            v-model="selectedRegion"
            :localdata="regionData"
            @change="onRegionChange"
          />
        </uni-forms-item>

        <uni-forms-item label="详细地址" required name="detail_address">
          <uni-easyinput 
            v-model="formData.detail_address"
            placeholder="街道、楼栋号等详细信息"
          />
        </uni-forms-item>

        <!-- 其他信息 -->
        <uni-forms-item label="民族" name="ethnicity">
          <uni-data-select 
            v-model="formData.ethnicity"
            :localdata="ethnicities"
          />
        </uni-forms-item>

        <uni-forms-item label="职业" name="occupation">
          <uni-easyinput 
            v-model="formData.occupation"
            placeholder="请输入职业"
          />
        </uni-forms-item>

        <uni-forms-item label="婚姻状况" name="marital_status">
          <uni-data-checkbox 
            v-model="formData.marital_status"
            :localdata="maritalStatus"
          />
        </uni-forms-item>
      </uni-card>

      <!-- 提交按钮 -->
      <view class="submit-btn">
        <button 
          type="primary" 
          :loading="submitting"
          @click="submitForm"
        >保存修改</button>
      </view>
    </uni-forms>
  </view>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { onLoad } from '@dcloudio/uni-app'

// 表单数据
const formData = reactive({
  avatar: '/static/default-avatar.png',
  name: '',
  gender: 1,
  birth_date: '',
  id_type: '身份证',
  id_number: '',
  phone: '',
  email: '',
  province_address: '',
  city_address: '',
  district_address: '',
  detail_address: '',
  ethnicity: '汉族',
  occupation: '',
  marital_status: '未婚'
})

// 数据字典
const idTypes = ref(['身份证', '护照', '军官证', '其他'])
const ethnicities = ref(['汉族', '壮族', '回族', '满族', '其他'])
const maritalStatus = ref([
  { value: '未婚', text: '未婚' },
  { value: '已婚', text: '已婚' },
  { value: '离异', text: '离异' },
  { value: '丧偶', text: '丧偶' }
])
const genders = ref([
  { value: 1, text: '男' },
  { value: 0, text: '女' }
])

// 表单验证规则
const rules = reactive({
  name: { rules: [{ required: true, errorMessage: '请输入姓名' }] },
  phone: {
    rules: [
      { required: true, errorMessage: '请输入手机号' },
      { pattern: /^1[3-9]\d{9}$/, errorMessage: '手机号格式不正确' }
    ]
  },
  id_number: {
    rules: [
      { required: true, errorMessage: '请输入证件号码' },
      { pattern: /^\d{17}[\dXx]$/, errorMessage: '身份证格式不正确' }
    ]
  },
  email: {
    rules: [
      { pattern: /^\w+@[a-z0-9]+\.[a-z]{2,4}$/, errorMessage: '邮箱格式不正确' }
    ]
  }
})

// 获取用户信息
const getUserInfo = async () => {
  try {
    const res = await uni.request({
      url: '/api/user/info',
      method: 'GET'
    })
    Object.assign(formData, res.data)
  } catch (error) {
    uni.showToast({ title: '获取信息失败', icon: 'none' })
  }
}

// 提交表单
const submitting = ref(false)
const submitForm = async () => {
  try {
    submitting.value = true
    await uni.request({
      url: '/api/user/update',
      method: 'POST',
      data: formData
    })
    uni.showToast({ title: '修改成功' })
  } catch (error) {
    uni.showToast({ title: '修改失败', icon: 'none' })
  } finally {
    submitting.value = false
  }
}

// 更换头像
const changeAvatar = async () => {
  try {
    const res = await uni.chooseImage({ count: 1 })
    const tempFile = res.tempFiles[0]
    
    // 上传头像
    const uploadRes = await uni.uploadFile({
      url: '/api/upload/avatar',
      filePath: tempFile.path,
      name: 'file'
    })
    
    formData.avatar = uploadRes.data.url
  } catch (error) {
    console.error('更换头像失败:', error)
  }
}

onMounted(() => {
  getUserInfo()
})
</script>

<style lang="scss" scoped>
.profile-container {
  padding: 20rpx;
  background-color: #f5f7fb;
  min-height: 100vh;

  .avatar-section {
    position: relative;
    width: 160rpx;
    height: 160rpx;
    margin: 40rpx auto;
    border-radius: 50%;
    overflow: hidden;
    
    .avatar {
      width: 100%;
      height: 100%;
    }
    
    .edit-icon {
      position: absolute;
      right: 10rpx;
      bottom: 10rpx;
      background: rgba(0,0,0,0.5);
      padding: 8rpx;
      border-radius: 50%;
    }
  }

  .submit-btn {
    margin: 40rpx;
    
    button {
      border-radius: 50rpx;
    }
  }
}

::v-deep .uni-forms-item__label {
  font-weight: bold !important;
  color: #333 !important;
}
</style>